/************************************************************************************
* PlayerWindow.cpp                                                                  *
*                                                                                   *
* Copyright (C) 2011 Varuna L Amachi                                                *
*                                                                                   *
* This program is free software; you can redistribute it and/or modify              *
* it under the terms of the GNU General Public License as published by              *
* the Free Software Foundation; either version 2 of the License, or any             *
* later version.                                                                    *
*                                                                                   *
* This program is distributed in the hope that it will be useful, but               *
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY        *
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for       *
* more details. You should have received a copy of the GNU General Public           *
* License along with this program; if not, write to the Free Software Foundation,   *
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA                       *
*                                                                                   *
*************************************************************************************/

#include "PlayerWindow.h"
#include "common/SizeConstants.h"
#include "common/Constants.h"
#include "collector/CollectorView.h"
#include "YContextImpl.h"
#include "interfaces/Playlist.h"
#include "components/HistoryManager.h"
#include "components/RecentAdditionsManager.h"
#include "components/track_browser/TrackBrowser.h"

#include <QtGui>
#include <QLinearGradient>
#include <QSizePolicy>

using namespace Phonon;


PlayerWindow::PlayerWindow(QWidget *parent) :
    QMainWindow(parent)
{
    m_oldMan = new QWidget(this);
    m_mainLayout    = new QHBoxLayout();
    m_playerLayout= new QVBoxLayout();
    m_player        = new PlayerWidget();//new PlayerWidget(this);
    m_playlistWidget= new PlaylistWidget();
    m_manager       = new YampManager();

    Collector::init(this);
    setUpUI();
    setupManager();
    makeConnections();
    setWindowTitle("YAMP");
    setWindowIcon(QIcon(":/yamp"));
}


void PlayerWindow::showEvent(QShowEvent *evt) {
    QMainWindow::showEvent(evt);
}



PlayerWindow::~PlayerWindow() {
    delete m_player;
    delete m_playlistWidget;
}



void PlayerWindow::setUpUI() {
    m_playerLayout->addWidget(m_player);
    m_playerLayout->addWidget(m_playlistWidget);
    m_mainLayout->addLayout(m_playerLayout);
    m_mainLayout->addWidget(m_manager);
    m_oldMan->setLayout(m_mainLayout);
    setCentralWidget(m_oldMan);

    QShortcut* seekForword = new QShortcut(this);
    seekForword->setContext(Qt::ApplicationShortcut);
    seekForword->setKey(QKeySequence(Qt::CTRL+ Qt::Key_W));
    seekForword->setAutoRepeat(true);
    connect(seekForword, SIGNAL(activated()), m_player, SLOT(seekForword()));

    QShortcut* seekBackword = new QShortcut(this);
    seekForword->setContext(Qt::ApplicationShortcut);
    seekBackword->setKey(QKeySequence(Qt::CTRL+ Qt::Key_Q));
    seekBackword->setAutoRepeat(true);
    connect(seekBackword, SIGNAL(activated()), m_player, SLOT(seekBackword()));

    m_player->setMaximumSize(FIRST_SPLITTER_WIDTH, PLAYER_WIDGET_HEIGHT);
    m_player->setMinimumSize(FIRST_SPLITTER_WIDTH, PLAYER_WIDGET_HEIGHT);

    m_playlistWidget->setMaximumWidth(FIRST_SPLITTER_WIDTH);
    m_playlistWidget->setMinimumWidth(FIRST_SPLITTER_WIDTH);

    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
//    m_player->setStyleSheet("background-image: url(:/player); "
//                            "color: #ADD8E6;");


}


void PlayerWindow::setupManager() {
    YContextImpl *context = new YContextImpl(m_player,
                                            dynamic_cast<Yamp::Playlist*>(m_playlistWidget->model()),
                                            m_manager);
    CollectorView* collector = new CollectorView(context, m_manager);
    HistoryManager *history  = new HistoryManager(context, m_manager);
    RecentAdditionsManager *recentAdditions = new RecentAdditionsManager(context, m_manager);
    TrackBrowser *browser = new TrackBrowser(context, m_manager);
    m_manager->addComponent(browser);
    m_manager->addComponent(collector);
    m_manager->addComponent(history);
    m_manager->addComponent(recentAdditions);

}



void PlayerWindow::makeConnections() {
    connect(m_playlistWidget->view(), SIGNAL(activated(QModelIndex)), m_playlistWidget->model(), SLOT(selectIndex(QModelIndex)));
    connect(m_player, SIGNAL(nextClicked()), m_playlistWidget->model(), SLOT(selectNext()));
    connect(m_player, SIGNAL(prevClicked()), m_playlistWidget->model(), SLOT(selectPrev()));
    connect(m_playlistWidget->model(), SIGNAL(selected(MediaItem*, int)), m_player, SLOT(setSource(MediaItem*)));
    connect(m_playlistWidget->model(), SIGNAL(playlistChanged()), this, SLOT(updatePlayerActions()));
    connect(m_playlistWidget->model(), SIGNAL(selected(MediaItem*,int)),this,  SLOT(updatePlayerActions()));
    connect(m_playlistWidget->view(), SIGNAL(clicked(QModelIndex)), this, SLOT(updatePlayerActions()));
    connect(m_playlistWidget->model(), SIGNAL(selected(MediaItem*,int)), this, SLOT(updatePlayerActions()));
    connect(m_playlistWidget->model(), SIGNAL(randomConfigChanged(bool)), this, SLOT(updatePlayerActions()));
    connect(m_playlistWidget->model(), SIGNAL(repeatConfigChanged(LoopType,LoopType)), this, SLOT(updatePlayerActions()));
    connect(m_player, SIGNAL(finished()), this, SLOT(trackFinished()));
    connect(m_playlistWidget->model(), SIGNAL(clearingPlaylist()), m_player, SLOT(stopAndClear()));
    connect(m_playlistWidget->model(), SIGNAL(removingCurrentItem()), m_player, SLOT(stopAndClear()));
    connect(m_player, SIGNAL(contentDropped(QList<QUrl>)), m_playlistWidget, SLOT(addUrls(QList<QUrl>)));
    connect(m_player, SIGNAL(yampSolo(bool)), this, SLOT(showPlayer(bool)));
    CollectorView* collector = dynamic_cast<CollectorView*>(m_manager->component(CollectorView::NAME));
    connect(collector->model(), SIGNAL(modelItemChanged(MediaItem*)), this, SLOT(itemChanged(MediaItem*)));
    connect(Collector::get(), SIGNAL(aboutToRemoveItems(QList<QString>*)),
            this, SLOT(collectorItemsDeleted(QList<QString>*)));
}


void PlayerWindow::showPlayer(bool val) {
    if(! val) {
        m_geometry = this->saveGeometry();
        m_playlistWidget->hide();
        m_manager->hide();
        m_mainLayout->update();
        this->setWindowState(((Qt::WindowStates)(~Qt::WindowMaximized & Qt::WindowNoState)));
        this->setMaximumSize(FIRST_SPLITTER_WIDTH, PLAYER_WIDGET_HEIGHT);
    }
    else {
        m_playlistWidget->setVisible(true);
        m_manager->setVisible(true);
        this->setMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
        this->restoreGeometry(m_geometry);
    }
    m_player->parentWidget()->layout()->invalidate();
    QWidget *parent = m_player->parentWidget();
    while (parent) {
        parent->adjustSize();
        parent = parent->parentWidget();
    }
}  void collectionDeletionStarted();
void collectionDeletionEnded();


void PlayerWindow::updatePlayerActions() {
    m_player->setNextEnabled(m_playlistWidget->model()->hasNext());
    m_player->setPrevEnabled(m_playlistWidget->model()->hasPrev());

}

void PlayerWindow::playSelected() {
    QItemSelectionModel* selModel = m_playlistWidget->view()->selectionModel();
    if(selModel != NULL && ! selModel->selection().empty()) {
        QModelIndex index = selModel->selectedRows().at(0);
        m_playlistWidget->model()->selectIndex(index);
    }
}

void PlayerWindow::disablePlayerActions() {
    m_player->setPlayEnabled(false);
    m_player->setStopEnabled(false);
    m_player->setNextEnabled(false);
    m_player->setPrevEnabled(false);
}

void PlayerWindow::trackFinished() {
    if(m_playlistWidget->model()->hasNext()) {
        m_playlistWidget->model()->selectNext();
    }
}


void PlayerWindow::itemChanged(MediaItem *item) {
    MediaItem* curItem = m_player->currentTrack();
    if( curItem != NULL && curItem->itemType() == CollectorItem::ITEM_TYPE &&
        item->itemType() == CollectorItem::ITEM_TYPE) {
        CollectorItem* colItem = (CollectorItem*)item;
        if(colItem != NULL && curItem->trackId() == colItem->trackId()) {
            m_player->currentItemChanged(item);
        }
    }
}


void PlayerWindow::collectorItemsDeleted(QList<QString>* ids) {
    MediaItem* curItem = m_player->currentTrack();
    if(curItem != NULL &&
            m_player->state() == Phonon::PlayingState ||
            m_player->state() == Phonon::PausedState) {
        for(int i = 0; i < ids->size(); ++i) {
            if(curItem->trackId() == ids->at(i)) {
                m_player->stopAndClear();
                break;
            }
        }
    }
    m_playlistWidget->model()->itemRemoved(ids);
    m_playlistWidget->view()->repaint();
}


//void PlayerWindow::collectionDeletionStarted() {
//    m_progressDialog->show();
//}


//void PlayerWindow::collectionDeletionEnded() {
//    m_progressDialog->hide();
//}
